package com.secneo.appshare.threads;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

import com.secneo.appshare.api.RemoteApi.OtherUserApp;
import com.secneo.appshare.api.RemoteApi.OtherUserApps;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;

public class OtherUserAppThread extends Thread {
	
	private static final String TAG = "OtherUserAppThread";
	private String uid;
	private String other_uid;
	
	private Context ctx;
	private Handler handler;
	private OtherUserApps otherUserApp;
	private boolean isStop;
	
	public OtherUserAppThread(Context ctx, Handler handler, String uid, String other_uid) {
		this.ctx = ctx;
		this.handler = handler;
		this.uid = uid;
		this.other_uid = other_uid;
		isStop = false;
	}
	
	public void stopThread() {
		isStop = true;
	}
	public OtherUserApps getOtherUserApps() {
		return otherUserApp;
	}
	
	public void run() {
		try {
			RemoteApiImpl remoteApi = new RemoteApiImpl();
			otherUserApp = remoteApi.getOtherUserApps(ctx, uid, other_uid);
			if (otherUserApp == null) 
			{
				Message msg = new Message();
				msg.what = Constants.MSG_GET_OTHER_USER_ERROR;
				handler.sendMessage(msg);
				return;
			}
			if (!otherUserApp.status.equals("ok")) 
			{
				Message msg = new Message();
				msg.what = Constants.MSG_GET_OTHER_USER_STATUS_ERROR;
				handler.sendMessage(msg);
				return;
			}
			
			Message msg = new Message();
			msg.what = Constants.MSG_GET_OTHER_USER_STATUS_OK;
			handler.sendMessage(msg);
			
			List<OtherUserApp> otherUserAppList = otherUserApp.otherUserAppList;
			for(int i = 0; i < otherUserAppList.size(); i++) 
			{
				if (isStop) 
					return;
				OtherUserApp app = otherUserAppList.get(i);
				Drawable dw = Util.getDrawableFromCache(ctx, app.icon_url);
				if (dw != null) 
				{
					app.icon_drawable = dw;
					Message iconmsg = new Message();
					iconmsg.what = Constants.MSG_GET_OTHER_USER_APP_ICON_FINISH;
					handler.sendMessage(iconmsg);
				}
			}
			
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
